package com.feige.utils.file.impl;


import com.feige.utils.file.FsUtils;
import com.feige.utils.file.pojo.FSInfo;
import com.feige.utils.file.FileUdService;
import com.feige.utils.file.pojo.UploadInfo;
import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashSet;
import java.util.Set;

/**
 * @author feige<br />
 * @ClassName: FastDfsUtil <br/>
 * @Description: <br/>
 * @date: 2021/9/24 17:01<br/>
 */
public class FastDfsFileUdServiceImpl implements FileUdService {

    Logger logger = LoggerFactory.getLogger(FastDfsFileUdServiceImpl.class);

    private final FastFileStorageClient fastFileStorageClient;

    public FastDfsFileUdServiceImpl(FastFileStorageClient fastFileStorageClient) {
        this.fastFileStorageClient = fastFileStorageClient;
    }


    @Override
    public FSInfo upload(UploadInfo uploadInfo) {
        Set<MetaData> metaData = uploadInfo.getMetaDataSet();
        if (metaData == null){
            metaData = new HashSet<>();
        }
        String objectName = uploadInfo.getFullFileName();
        metaData.add(new MetaData("fileName", objectName));
        StorePath storePath = fastFileStorageClient.uploadFile(uploadInfo.getInputStream(), uploadInfo.getFileSize(), uploadInfo.getFileExtName(), metaData);
        FSInfo fsInfo = new FSInfo();
        fsInfo.setPath(storePath.getPath());
        fsInfo.setGroup(storePath.getGroup());
        fsInfo.setStorageType(this.getType());
        fsInfo.setOriginalFilename(uploadInfo.getOriginalFilename());
        logger.info("{}文件上传成功",uploadInfo.getFileName());
        return fsInfo;
    }

    @Override
    public InputStream getFileInputStream(String objectName) {
        int indexOf = objectName.lastIndexOf("/");
        if (indexOf != -1){
            String group = objectName.substring(indexOf + 1);
            String path = objectName.substring(0,indexOf + 1);
            byte[] bytes = fastFileStorageClient.downloadFile(group, path, new DownloadByteArray());
            return new ByteArrayInputStream(bytes);
        }
        throw new IllegalArgumentException("FastDFS下载文件名必须含group和文件名");
    }

    @Override
    public String getType() {
        return FsUtils.FAST_DFS;
    }
}
